import router from '@/router'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import {getToken} from '@/utils/token'
import useLoginStore from '@/stores/login-store'
import useMenuStore from '@/stores/menu-store'


//全局前置路由守卫
router.beforeEach((to, from, next) => {
    NProgress.start()
    const whileList = ['/login']
    const loginStore = useLoginStore()
    const menuStore = useMenuStore()
    if (whileList.includes(to.path)) {
        next()
    } else {
        if (to.path === '/login') {
            next('/')
        } else {
            if (getToken()) {
                // 判断角色是否为空 有角色 直接跳转目标页
                if (loginStore.userInfo?.roleAndPermissions?.length) {
                    next()
                } else {
                    loginStore.getUserInfo().then(() => {
                        // 未分配角色权限时，跳转到登录页
                        if(!loginStore.userInfo?.roleAndPermissions?.length){
                            next({path: '/login'})
                            return false
                        }
                        // 如果未获取到菜单树，则获取菜单树
                        if ( !menuStore?.layoutMenuTree?.length) {
                            menuStore?.getUserMenuTree()?.then()
                        }
                        next({...to, replace: true})
                    }).catch(() => {
                        window.sessionStorage.clear()
                        next({path: '/login'})
                    })
                }
            } else {
                next(`/login?redirect=${to.fullPath}`) // 否则全部重定向到登录页
            }
        }
    }
})
router.afterEach((to) => {
    if (to.meta.title) {
        document.title = '后台管理系统｜'+to.meta.title
    }
    NProgress.done()
})
